# -*- coding: utf-8 -*-
"""
@Time ： 2022/11/26 19:12
@Auth ： GaoShuai
@File ：CommonUtils.py
@IDE ：PyCharm
"""
import os
import re
import time
from concurrent.futures import ThreadPoolExecutor

import cv2
import numpy
import numpy as np


def get_nparray_max_index(input_array: numpy.ndarray, k: int):
    top_k = numpy.argpartition(input_array, k)
    input_shape = input_array.shape
    max_index = numpy.argmax(input_array)
    x = int(max_index / input_shape[0])
    y = int(max_index - x * input_shape[0])
    return x, y


def get_nparray_min_index(input_array: numpy.ndarray):
    input_shape = input_array.shape
    max_index = numpy.argmin(input_array)
    x = int(max_index / input_shape[0])
    y = int(max_index - x * input_shape[0])
    return x, y


def get_process_pooling(max_workers=2):
    """
    可以使用pool.submit(self.visualizer.display_current_results, show_batch, epoch, i,True, show_interval)
    来提交函数
    :param max_workers:
    :return:
    """
    pool = ThreadPoolExecutor(max_workers=max_workers)
    return pool


def get_current_timestamp():
    time_stamp = time.strftime('%Y_%m_%d_%H_%M', time.localtime(time.time()))
    return time_stamp


def check_create_dir(dir_path):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)


def get_project_root_path():
    return r"D:\gs\code\MARExperimentOne"


def find_number_from_str(input_str):
    """
    find numbers from a string
    :param input_str: string
    :return: the list of all number
    """
    return_str = re.findall("\d+", input_str)
    return return_str


def normalize_new_S(img):
    """
    突然有个想法，归一化的方式使用的有问题，如果直接归一化到[0,255]的方式，势必会把最大值拉大
    因此可以使用固定公式归一化的方式。同样针对取值为数万的投影域图也可以使用同样的方式
    92320 这个数来源于 255 * 256 * 2^0.5
    这样归一化的导致的值都太小
    经过遍历  最大值在32767左右  使用33000
    :param img:
    :return:
    """
    img = (img / 33000) * 2 - 1
    return img


def normalize_S_InDuDoNet(img):
    """
    突然有个想法，归一化的方式使用的有问题，如果直接归一化到[0,255]的方式，势必会把最大值拉大
    因此可以使用固定公式归一化的方式。同样针对取值为数万的投影域图也可以使用同样的方式
    92320 这个数来源于 255 * 256 * 2^0.5
    这样归一化的导致的值都太小
    经过遍历  最大值在32767左右  使用33000
    InDuDoNet中正弦域的值域为[0,4]
    :param img:
    :return:
    """
    img = (img / 33000) * 4
    return img


def normalize_X_InDuDoNet(img):
    """
    InDuDoNet中正弦域的值域为[0,1]
    :param img:
    :return:
    """
    img = img / 255
    return img


def normalize_new_S_inverse(img):
    img = (img + 1) / 2 * 33000
    return img


def normalize_to255(img):
    if isinstance(img, np.ndarray):
        if np.min(img) == -1:
            img = (img + 1) / 2 * 255
        else:
            data_min = np.min(img)
            data_max = np.max(img)
            img = (img - data_min) / (data_max - data_min)
            img = img.astype(np.float32)
            img = img * 255.0
        return img


def cv2_show_function(show_img_list, if_save=False, save_path="gs_function_save"):
    # print(show_img_list[0][1].__name__)
    for show_img_tuple in show_img_list:
        if isinstance(show_img_tuple[1], np.ndarray):
            if len(show_img_tuple[1].shape) == 2:
                tmp_min_position = np.argmin(show_img_tuple[1])
                show_img_numpy = normalize_to255(show_img_tuple[1])
                show_img_numpy = show_img_numpy.astype(np.uint8)
                cv2.imshow(show_img_tuple[0], show_img_numpy)

                if if_save:
                    cv2.imwrite(os.path.join(save_path, show_img_tuple[0] + '.png'), show_img_numpy)
            elif len(show_img_tuple[1].shape) == 3:
                show_img_numpy = normalize_to255(show_img_tuple[1][0])
                show_img_numpy = show_img_numpy.astype(np.uint8)
                cv2.imshow(show_img_tuple[0], show_img_numpy)
                if if_save:
                    cv2.imwrite(os.path.join(save_path, show_img_tuple[0] + '.png'), show_img_numpy)
            elif len(show_img_tuple[1].shape) == 4:
                show_img_numpy = normalize_to255(show_img_tuple[1][0][0])
                show_img_numpy = show_img_numpy.astype(np.uint8)
                cv2.imshow(show_img_tuple[0], show_img_numpy)
                if if_save:
                    cv2.imwrite(os.path.join(save_path, show_img_tuple[0] + '.png'), show_img_numpy)
        else:
            show_img_numpy = show_img_tuple[1][0][0].clone().cpu().detach().numpy()
            show_img_numpy = normalize_to255(show_img_numpy)
            show_img_numpy = show_img_numpy.astype(np.uint8)
            cv2.imshow(show_img_tuple[0], show_img_numpy)
            cv2.imwrite(os.path.join(save_path, show_img_tuple[0] + '.png'), show_img_numpy)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    pass


def cv2_show_function_negative(show_img_list, if_save=False, save_path="gs_function_save"):
    # print(show_img_list[0][1].__name__)
    for show_img_tuple in show_img_list:
        if isinstance(show_img_tuple[1], np.ndarray):
            if len(show_img_tuple[1].shape) == 2:
                show_img_numpy = (show_img_tuple[1] + 1) / 2 * 255
                show_img_numpy = show_img_numpy.astype(np.uint8)
                cv2.imshow(show_img_tuple[0], show_img_numpy)
                if if_save:
                    cv2.imwrite(os.path.join(save_path, show_img_tuple[0] + '.png'), show_img_numpy)
            elif len(show_img_tuple[1].shape) == 3:
                show_img_numpy = (show_img_tuple[1][0] + 1) / 2 * 255
                show_img_numpy = show_img_numpy.astype(np.uint8)
                cv2.imshow(show_img_tuple[0], show_img_numpy)
                if if_save:
                    cv2.imwrite(os.path.join(save_path, show_img_tuple[0] + '.png'), show_img_numpy)
            elif len(show_img_tuple[1].shape) == 4:
                show_img_numpy = (show_img_tuple[1][0][0] + 1) / 2 * 255
                show_img_numpy = show_img_numpy.astype(np.uint8)
                cv2.imshow(show_img_tuple[0], show_img_numpy)
                if if_save:
                    cv2.imwrite(os.path.join(save_path, show_img_tuple[0] + '.png'), show_img_numpy)
        else:
            show_img_numpy = show_img_tuple[1][0][0].clone().cpu().detach().numpy()
            show_img_numpy = (show_img_numpy + 1) / 2 * 255
            show_img_numpy = show_img_numpy.astype(np.uint8)
            cv2.imshow(show_img_tuple[0], show_img_numpy)
            if if_save:
                cv2.imwrite(os.path.join(save_path, show_img_tuple[0] + '.png'), show_img_numpy)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    pass


if __name__ == '__main__':
    print(find_number_from_str("gated_conv_100_inference_10.png"))
